package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.BuyCartBean;
import com.project.mapper.IBuyCartMapper;
import com.project.service.IBuyCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class BuyCartServiceImpl implements IBuyCartService {
    @Autowired
    private IBuyCartMapper buyCartMapper;

    @Override
    public List<BuyCartBean> findByUserId(Integer userId) {

        return buyCartMapper.findByUserId(userId);
    }

    @Override
    public void del(Integer id) {
        buyCartMapper.deleteById(id);
    }

    @Override
    public void add(BuyCartBean buyCart) {
        QueryWrapper<BuyCartBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", buyCart.getUserId());
        qw.eq("fk_productId", buyCart.getProductId());
        BuyCartBean OldBuyCart = buyCartMapper.selectOne(qw);

        if (OldBuyCart != null) {
            OldBuyCart.setNum(OldBuyCart.getNum() + buyCart.getNum());
            buyCartMapper.updateById(OldBuyCart);
        }else {
            buyCartMapper.insert(buyCart);
        }

    }

    @Override
    public void update(Integer id, Integer price, Integer num) {
        BuyCartBean buyCart = buyCartMapper.selectById(id);

        buyCart.setPrice(price);
        buyCart.setNum(num);

        buyCartMapper.updateById(buyCart);
    }
}
